package controllers

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"go_payment/app/library"
	"go_payment/app/param_model"
	"go_payment/dao"
	"net/http"
	"strings"
)

//Pay 支付入口
func Pay(c *gin.Context) {
	var trade param_model.Trade
	if err := c.ShouldBind(&trade); err != nil {
		library.Fail(c, "数据绑定出错")
		return
	}
	//数据校验
	if err := trade.Validate(); err != nil {
		library.Fail(c, fmt.Sprint(err))
		return
	}
	//获取用户支付产品配置
	userProductConf := dao.GetProductUser(trade.GetMemberId(), trade.BankCode)
	if userProductConf.UserId == 0 {
		library.Fail(c, fmt.Sprintf("%d产品信息未开通", trade.BankCode))
		return
	}
	//获取渠道信息
	channelId, err := dao.GetChannelByProduct(userProductConf, &trade)
	if err != nil {
		library.Fail(c, fmt.Sprint(err))
		return
	}
	//获取渠道代码
	code := dao.GetChannelCode(channelId)
	if code == "" {
		library.Fail(c, "渠道信息不正确")
		return
	}
	trade.SetChannelId(channelId)

	//拆分渠道代码,目的让同一银行走同一个文件
	codeArr := strings.Split(code, "_")
	code = codeArr[0]

	//根据code找到具体对应的渠道，并获取返回的数据
	factory, err := library.PayFactory(code)
	if err != nil {
		library.Fail(c, fmt.Sprint(err))
		return
	}
	dto, err := factory.Pay(trade)
	if err != nil {
		library.Fail(c, fmt.Sprint(err))
	}
	library.Success(c, "获取成功", gin.H{"order_id": dto.TransId})
}

//Notify 异步通知地址
func Notify(c *gin.Context) {
	code := c.Param("code")
	code = strings.TrimSpace(code)
	obj, err := library.PayFactory(code)
	if err != nil {
		library.Fail(c, "渠道信息错误")
		return
	}
	err = obj.Notify()
	if err != nil {
		fmt.Println(err)
		dao.AddOrderInSet("2020091518232117514575798671")
	} else {
		c.String(http.StatusOK, "ok")
	}
}
